package com.avengers.core.model.db;


import com.avengers.core.model.DbColumn;

/**
 * @author yu.wang
 * @since 2018-04-18 下午2:30
 */
public enum DBFunction {
    /**
     * count
     */
    COUNT,
    SUM,
    CONCAT,
    SUBSTR,
    IF;

    public static String count(Object value) {
        return COUNT.name() + SqlKey.BRACKETS_LEFT.trim() + (value instanceof DbColumn ? ((DbColumn) value).sqlColumn() : value.toString()) + SqlKey.BRACKETS_RIGHT.trim();
    }

    public static String sum(DbColumn column) {
        return SUM.name() + SqlKey.BRACKETS_LEFT.trim() + column.sqlColumn() + SqlKey.BRACKETS_RIGHT.trim();
    }

    public static String concat(Object... objects) {
        if (null == objects || objects.length <= 0) {
            return SqlKey.EMPTY;
        }
        StringBuffer dbSb = new StringBuffer();
        dbSb.append(CONCAT).append(SqlKey.BRACKETS_LEFT.trim());
        for (int i = 0; i < objects.length; i++) {
            if (i != 0) {
                dbSb.append(SqlKey.COMMA);
            }
            if (objects[i] instanceof DbColumn) {
                dbSb.append(((DbColumn) objects[i]).sqlColumn());
            } else if (SqlKey.PARAM.equals(objects[i])) {
                dbSb.append(objects[i]);
            } else {
                dbSb.append(SqlKey.QUOTES).append(objects[i]).append(SqlKey.QUOTES);
            }
        }
        dbSb.append(SqlKey.BRACKETS_RIGHT.trim());
        return dbSb.toString();
    }

    public static String subStr(DbColumn column, int firstIndex, int length) {
        return SUBSTR.name() + SqlKey.BRACKETS_LEFT.trim() + column.sqlColumn() + SqlKey.COMMA + firstIndex + SqlKey.COMMA + length + SqlKey.BRACKETS_RIGHT.trim();
    }

    public static String ifNull(DbColumn column, String trueValue, String falseValue) {
        return IF.name() + SqlKey.BRACKETS_LEFT.trim() + column.sqlColumn() + SqlKey.IS_NULL + SqlKey.OR + column.sqlColumn() + SqlKey.IS_EMPTY + SqlKey.COMMA + trueValue + SqlKey.COMMA + falseValue + SqlKey.BRACKETS_RIGHT.trim();
    }
}
